﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.Common.Utility.EnumToos;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.BLL.BllExt;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace Matrix.MaKaYunShang.MagWeb.Controllers
{
    [Authorization]
    [Matrix.MaKaYunShang.Model.Attributes.Skip]
    public class OrdersController : BaseController
    {
        public ActionResult List(int orderStatus = -1)
        {
            ViewBag.OrderStatus = orderStatus;
            return View();
        }

        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult Listing(int draw, int start, int length, string keyWords, string orderNo, string startTime, string endTime, string shopName, int orderStatus = -1)
        {
            try
            {
                var pageIndex = (start / length) + 1;
                var orderData = "Id desc ";
                if (orderStatus == (int)CommonEnum.OrderStatus.ToBePaid ||
                    orderStatus == (int)CommonEnum.OrderStatus.NewOrder ||
                    orderStatus == (int)CommonEnum.OrderStatus.BeingDelivered)
                {
                    orderData = "Id asc ";
                }
                var shopIds = string.Empty;
                if (!string.IsNullOrEmpty(shopName))
                {
                    var shopList = ShopsBLL.Instance.GetListByName(shopName);
                    if (shopList.Count > 0)
                    {
                        shopIds = string.Join(",", shopList.Select(l => l.Id));
                    }
                    else
                    {
                        shopIds = "-1";
                    }
                }
                var theList = OrdersBLL.Instance.GetPagingList(MagModules, draw, pageIndex, length, keyWords, orderNo, startTime, endTime, shopIds, orderStatus, 0, orderData, true);
                theList.data.ForEach(o=>
                {
                    if (o.OrderStatus == CommonEnum.OrderStatus.NewOrder.ToString())
                    {
                        if (MagModules.FindAll(t => t
                            .Action.Equals("TransferOrder") && t
                                .Controller.Equals("Orders")).Count > 0)
                        {
                            o.Action +=
                                "<a data-target='#TransferOrderModal' data-toggle='modal' class='btn btn-info' onclick=transfer(" +
                                o.Id + ");>转移</a> ";
                        }
                    }
                });
                return Json(theList);
            }
            catch { }
            return Json(null);
        }

        public ActionResult Detail(int id, string returnUrl = null)
        {
            var orderModel = OrdersBLL.Instance.GetModel(id);
            var viewOrder = new ViewOrdersDto();
            if (orderModel != null)
            {
                viewOrder.Id = orderModel.Id;
                viewOrder.OrderNo = orderModel.OrderNo;
                viewOrder.OrderTime = orderModel.OrderTime.ToString();
                viewOrder.OrderStatus = ((CommonEnum.OrderStatus)orderModel.OrderStatus).GetDescription();
                viewOrder.ShopId = orderModel.ShopId;
                if (orderModel.ShopId > 0)
                {
                    var shop = ShopsBLL.Instance.GetModel(orderModel.ShopId);
                    if (shop != null)
                    {
                        viewOrder.ShopName = shop.Name;
                        viewOrder.ShopLegalPersonMobile = shop.LegalPersonMobile;
                        viewOrder.ShopTel = shop.Tel;
                    }
                }
                viewOrder.ShopCustomerNumber = orderModel.ShopCustomerNumber;
                viewOrder.OldOrderPhone = orderModel.OldOrderPhone;
                viewOrder.CommodityQuantity = orderModel.CommodityQuantity;
                viewOrder.PayPrice = orderModel.PayPrice.ToString();
                viewOrder.DiscountPrice = orderModel.DiscountPrice.ToString();
                viewOrder.NormalPrice = orderModel.NormalPrice.ToString();
                viewOrder.RandomPayDiscount = orderModel.RandomPayDiscount;
                viewOrder.CouponValue = orderModel.CouponValue;

                viewOrder.CouponResume = OrdersBLL.Instance.GetOrderCouponUseResume(orderModel.Id).Replace("<br/>", "\r\n");

                viewOrder.PayWay = ((CommonEnum.OrderPayWay)orderModel.PayWay).GetDescription();
                if (orderModel.PayPrice == 0 && !string.IsNullOrWhiteSpace(viewOrder.CouponResume))
                {
                    viewOrder.PayWay = "电子水票（券）支付";
                }

                viewOrder.ReceiverName = orderModel.ReceiverName;
                viewOrder.ReceiverPhone = orderModel.ReceiverPhone;
                viewOrder.ReceiverAddress = orderModel.ReceiverAddress;
                viewOrder.Remark = orderModel.Remark;
                viewOrder.SysRemark = orderModel.SysRemark;
                if (orderModel.AssignerAccountId > 0)
                {
                    viewOrder.AssignTime = orderModel.AssignTime != null ? orderModel.AssignTime.ToString() : null;
                }
                if (orderModel.DeliveryAccountId > 0)
                {
                    var deliveryAccount = McAccountsBLL.Instance.GetModel(orderModel.DeliveryAccountId);
                    if (deliveryAccount != null)
                    {
                        viewOrder.DeliveryDisplayName = deliveryAccount.DisplayName;
                        viewOrder.DeliveryMobile = deliveryAccount.Mobile;
                    }
                    viewOrder.DeliveryTime = orderModel.DeliveryTime != null ? orderModel.DeliveryTime.ToString() : null;
                }
                viewOrder.ReceivingTime = orderModel.ReceivingTime != null ? orderModel.ReceivingTime.ToString() : null;
                viewOrder.FinishTime = orderModel.FinishTime != null ? orderModel.FinishTime.ToString() : null;
                viewOrder.CancelTime = orderModel.CancelTime != null ? orderModel.CancelTime.ToString() : null;
                viewOrder.RejectTime = orderModel.RejectTime != null ? orderModel.RejectTime.ToString() : null;
                viewOrder.RemindTime = orderModel.RemindTime != null ? orderModel.RemindTime.ToString() : null;
                viewOrder.ConsumerSendTime = orderModel.ConsumerSendTime;
                viewOrder.OrderDetailList = OrderDetailBLL.Instance.GetModelList("OrderId=" + orderModel.Id);
                var consumerModel = ConsumerBLL.Instance.GetModel(orderModel.ConsumerId);
                if (consumerModel != null)
                {
                    ViewBag.NickName = consumerModel.NickName + "（客户编号：" + consumerModel.Id + "）";
                }
            }
            return View(viewOrder);
        }

        /// <summary>
        /// 所有数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult GetCount()
        {
            var data = OrdersBLL.Instance.GetTotalCount();
            return Json(data);
        }

        /// <summary>
        /// 搜索店铺（转移订单）
        /// </summary>
        [HttpPost]
        [Matrix.MaKaYunShang.Model.Attributes.Skip]
        public JsonResult GetShopList(int orderId, string keyWords)
        {
            var result = new Result<List<Shops>>();
            var sysConfig = SysConfigBLL.Instance.GetModelList().FirstOrDefault();
            if (sysConfig != null)
            {
                var order = OrdersBLL.Instance.GetModel(orderId);
                if (order != null)
                {
                    var searchShopRadius = string.IsNullOrEmpty(keyWords) ? sysConfig.SearchShopRadius : int.MaxValue;
                    result = new OrderExtBll().SearchShopsMatchedToTransmit(orderId, order.ConsumerId, order.ShopId, searchShopRadius, keyWords);
                    if (result.Data != null)
                    {
                        result.Data.RemoveAll(l => l.Id == order.ShopId);
                    }
                }
                else
                {
                    result.Message = "订单不存在！";
                }
            }
            else
            {
                result.Message = "系统配置错误！";
            }
            return Json(result);
        }

        /// <summary>
        /// 转移订单
        /// </summary>
        [HttpPost]
        public JsonResult TransferOrder(int orderId, int shopId)
        {
            var result = new Result<int>();
            var order = OrdersBLL.Instance.GetModel(orderId);
            if (order != null)
            {
                if (order.OrderIdCopiedFrom == 0)
                {
                    result = new OrderExtBll().TransmitOrderToNewShop(orderId, order.ConsumerId, shopId);
                }
                else
                {
                    result.Message = "该订单已被转移过，不可再次转移！";
                }
            }
            else
            {
                result.Message = "订单不存在！";
            }
            return Json(result);
        }

        /// <summary>
        /// 导出订单
        /// </summary>
        /// <remarks>2016-08-26 万乐园 创建</remarks>
        [HttpPost]
        public JsonResult ExportOrders(string keyWords, string orderNo, string startTime, string endTime, string shopName, int orderStatus = -1)
        {
            var result = new Result();
            try
            {
                var shopIds = string.Empty;
                if (!string.IsNullOrEmpty(shopName))
                {
                    var shopList = ShopsBLL.Instance.GetListByName(shopName);
                    shopIds = shopList.Count > 0 ? string.Join(",", shopList.Select(l => l.Id)) : "-1";
                }
                var orderList = OrdersBLL.Instance.GetExportOrderList(keyWords, orderNo, startTime, endTime, shopIds, orderStatus);

                #region 生成excel文件
                var book = new HSSFWorkbook();
                var sheet = book.CreateSheet("订单数据");
                var titleRow = sheet.CreateRow(0);

                #region 表头
                titleRow.CreateCell(0).SetCellValue("销售日期");
                titleRow.CreateCell(1).SetCellValue("订单时间");
                titleRow.CreateCell(2).SetCellValue("订单号");
                titleRow.CreateCell(3).SetCellValue("支付流水号");
                titleRow.CreateCell(4).SetCellValue("条形码");
                titleRow.CreateCell(5).SetCellValue("购买产品");
                titleRow.CreateCell(6).SetCellValue("购买数量");
                titleRow.CreateCell(7).SetCellValue("产品单价");
                titleRow.CreateCell(8).SetCellValue("支付金额");
                titleRow.CreateCell(9).SetCellValue("优惠金额");
                titleRow.CreateCell(10).SetCellValue("支付方式");
                titleRow.CreateCell(11).SetCellValue("客户地址");
                titleRow.CreateCell(12).SetCellValue("客户姓名");
                titleRow.CreateCell(13).SetCellValue("客户电话");
                titleRow.CreateCell(14).SetCellValue("订单备注");
                titleRow.CreateCell(15).SetCellValue("订单状态");
                titleRow.CreateCell(16).SetCellValue("配送店铺电话");
                titleRow.CreateCell(17).SetCellValue("所属门店");
                titleRow.CreateCell(18).SetCellValue("门店账号");
                titleRow.CreateCell(19).SetCellValue("转移门店");
                titleRow.CreateCell(20).SetCellValue("转移门店账号");
                titleRow.CreateCell(21).SetCellValue("备注1");
                titleRow.CreateCell(22).SetCellValue("订单票券详情");
                #endregion

                var rowIndex = 1;
                for (var i = 0; i < orderList.Count; i++)
                {
                    var dataRow = sheet.CreateRow(rowIndex);
                    dataRow.CreateCell(0).SetCellValue(orderList[i].OrderTime.ToString());//销售日期
                    dataRow.CreateCell(1).SetCellValue(orderList[i].OrderTime.ToString());//订单日期
                    dataRow.CreateCell(2).SetCellValue(orderList[i].OrderNo);//订单号
                    var paymentRecords = PaymentRecordsBLL.Instance.GetModelList("OrderId=" + orderList[i].Id + " and PayResult=1").FirstOrDefault();
                    dataRow.CreateCell(3).SetCellValue(paymentRecords != null ? paymentRecords.WechatTransactionId : "");//支付流水号
                    dataRow.CreateCell(4).SetCellValue("");//条形码
                    dataRow.CreateCell(8).SetCellValue(orderList[i].PayPrice.ToString());//支付金额
                    dataRow.CreateCell(9).SetCellValue(orderList[i].RandomPayDiscount.ToString());//优惠金额

                    var payWayDes = ((CommonEnum.OrderPayWay)orderList[i].PayWay).GetDescription();
                    var couponResume = OrdersBLL.Instance.GetOrderCouponUseResume(orderList[i].Id).Replace("<br/>", "\r\n");
                    if (orderList[i].PayPrice == 0 && !string.IsNullOrWhiteSpace(couponResume))
                    {
                        payWayDes = "电子水票（券）支付";
                    }
                    dataRow.CreateCell(10).SetCellValue(payWayDes);//支付方式

                    dataRow.CreateCell(11).SetCellValue(orderList[i].ReceiverAddress);//客户地址
                    dataRow.CreateCell(12).SetCellValue(orderList[i].ReceiverName);//客户姓名
                    dataRow.CreateCell(13).SetCellValue(orderList[i].ReceiverPhone);//客户电话
                    dataRow.CreateCell(14).SetCellValue(orderList[i].Remark);//订单备注
                    dataRow.CreateCell(15).SetCellValue(((CommonEnum.OrderStatus)orderList[i].OrderStatus).GetDescription());//订单状态
                    var orderShop = ShopsBLL.Instance.GetModel(orderList[i].ShopId);
                    var orderShopTel = string.Empty;
                    var orderShopName = string.Empty;
                    var orderShopAccount = string.Empty;
                    if (orderShop != null)
                    {
                        orderShopTel = orderShop.Tel;
                        orderShopName = orderShop.Name;
                        var mcAccount = McAccountsBLL.Instance.GetModelList("ShopId=" + orderList[i].ShopId + " and AccountType=1").FirstOrDefault();
                        if (mcAccount != null)
                        {
                            orderShopAccount = mcAccount.UserName;
                        }
                    }
                    dataRow.CreateCell(16).SetCellValue(orderShopTel);//配送店铺电话
                    dataRow.CreateCell(17).SetCellValue(orderShopName);//所属门店
                    dataRow.CreateCell(18).SetCellValue(orderShopAccount);//门店账号
                    var transferShopName = string.Empty;
                    var transferShopAccount = string.Empty;
                    var transferOrder = OrdersBLL.Instance.GetModelList("OrderIdCopiedFrom=" + orderList[i].Id).FirstOrDefault();
                    if (transferOrder != null)
                    {
                        var transferShop = ShopsBLL.Instance.GetModel(transferOrder.ShopId);
                        if (transferShop != null)
                        {
                            transferShopName = transferShop.Name;
                            var transferMcAccount = McAccountsBLL.Instance.GetModelList("ShopId=" + transferOrder.ShopId + " and AccountType=1").FirstOrDefault();
                            if (transferMcAccount != null)
                            {
                                transferShopAccount = transferMcAccount.UserName;
                            }
                        }
                    }
                    dataRow.CreateCell(19).SetCellValue(transferShopName);//转移门店
                    dataRow.CreateCell(20).SetCellValue(transferShopAccount);//转移门店账号
                    dataRow.CreateCell(21).SetCellValue("");//备注1
                    dataRow.CreateCell(22).SetCellValue(couponResume);//订单票券详情
                    var orderDetailList = OrderDetailBLL.Instance.GetModelList("OrderId=" + orderList[i].Id);
                    for (var j = 0; j < orderDetailList.Count; j++)
                    {
                        var strNameExtensionText = string.Empty;
                        var commodityLibInfo =
                                    CommodityLibBLL.Instance.GetCommodityInfoByAppointedShopCommodityIds(
                                        orderDetailList[j].ShopCommodityId.ToString());

                        if (commodityLibInfo != null && commodityLibInfo.Count > 0)
                        {
                            if (commodityLibInfo[0].IsVirtual)
                            {
                                strNameExtensionText += "<font style='color:blue'>【" +
                                                      ((orderList[i].ConsumerOrderType ==
                                                        (int)CommonEnum.ConsumerOrderType.ShopConsumerOrder &&
                                                        commodityLibInfo[0].Id == 87)
                                                          ? "可提现"
                                                          : "不可提现") + "】</font>";
                            }
                        }

                        if (j == 0)
                        {
                            dataRow.CreateCell(5)
                                .SetCellValue(orderDetailList[j].CommodityName + strNameExtensionText +
                                              (orderDetailList[j].IsGift ? "【赠品】" : ""));//购买产品

                            dataRow.CreateCell(6).SetCellValue(orderDetailList[j].Quantity.ToString());//购买数量
                            dataRow.CreateCell(7).SetCellValue(orderDetailList[j].Price.ToString());//产品单价
                        }
                        else
                        {
                            rowIndex++;
                            var detailRow = sheet.CreateRow(rowIndex);
                            detailRow.CreateCell(0).SetCellValue(orderList[i].OrderTime.ToString());//销售日期
                            detailRow.CreateCell(1).SetCellValue(orderList[i].OrderTime.ToString());//订单日期
                            detailRow.CreateCell(2).SetCellValue(orderList[i].OrderNo);//订单号
                            detailRow.CreateCell(3).SetCellValue(paymentRecords != null ? paymentRecords.WechatTransactionId : "");//支付流水号
                            detailRow.CreateCell(4).SetCellValue("");//条形码
                            detailRow.CreateCell(5)
                                .SetCellValue(orderDetailList[j].CommodityName + strNameExtensionText +
                                              (orderDetailList[j].IsGift ? "【赠品】" : ""));//购买产品
                            detailRow.CreateCell(6).SetCellValue(orderDetailList[j].Quantity.ToString());//购买数量
                            detailRow.CreateCell(7).SetCellValue(orderDetailList[j].Price.ToString());//产品单价
                            detailRow.CreateCell(8).SetCellValue(orderList[i].PayPrice.ToString());//支付金额
                            detailRow.CreateCell(9).SetCellValue(orderList[i].RandomPayDiscount.ToString());//优惠金额
                            detailRow.CreateCell(10).SetCellValue(((CommonEnum.OrderPayWay)orderList[i].PayWay).GetDescription());//支付方式
                            detailRow.CreateCell(11).SetCellValue(orderList[i].ReceiverAddress);//客户地址
                            detailRow.CreateCell(12).SetCellValue(orderList[i].ReceiverName);//客户姓名
                            detailRow.CreateCell(13).SetCellValue(orderList[i].ReceiverPhone);//客户电话
                            detailRow.CreateCell(14).SetCellValue(orderList[i].Remark);//订单备注
                            detailRow.CreateCell(15).SetCellValue(((CommonEnum.OrderStatus)orderList[i].OrderStatus).GetDescription());//订单状态
                            detailRow.CreateCell(16).SetCellValue(orderShopTel);//配送店铺电话
                            detailRow.CreateCell(17).SetCellValue(orderShopName);//所属门店
                            detailRow.CreateCell(18).SetCellValue(orderShopAccount);//门店账号
                            detailRow.CreateCell(19).SetCellValue(transferShopName);//转移门店
                            detailRow.CreateCell(20).SetCellValue(transferShopAccount);//转移门店账号
                            detailRow.CreateCell(21).SetCellValue("");//备注1
                            detailRow.CreateCell(22).SetCellValue(couponResume);//订单票券详情
                        }
                    }
                    rowIndex++;
                }

                var filename = DateTime.Now.ToString("yyyyMMddHHmmss") + CommonHelper.GetGuidKey(6) + ".xls";
                var path = System.Web.HttpContext.Current.Server.MapPath("/Files/Order/" + filename);
                if (!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath("/Files/Order/")))
                {
                    Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath("/Files/Order/"));
                }
                using (var fs = System.IO.File.Create(path))
                {
                    book.Write(fs);
                }
                #endregion

                result.Status = true;
                result.Message = "/Files/Order/" + filename;
            }
            catch (Exception ex)
            {
                Logger.Error("OrdersController -- ExportOrders" + ex);
                result.Message = "系统未知错误，请联系管理员";
            }
            return Json(result);
        }
    }
}